package com.niuwa.p2p.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import com.niuwa.p2p.service.filesystem.FileSystem;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 
 * 文件下载
 * ServerContext环境
 * 
 * 
 * @author jishengjun
 * 
 */
public class FileDownLoadAction extends ActionSupport {

	private static final long serialVersionUID = -3492180007735079277L;
	
	/** 下载文件ID*/
	private String fileID;
	
	/** 下载文件流*/
	private InputStream inputStream;
	
	/** 下载文件名*/
	private String fileName;
	
	/** 文件系统*/
	@Autowired
	private FileSystem fileSystem;
	
	@Autowired
	private HttpServletRequest request;
	
	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public String getFileID() {
		return fileID;
	}

	public void setFileID(String fileID) {
		this.fileID = fileID;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	/**
	 * 文件下载
	 * 根据文件路径,文件类型实施下载
	 * 
	 */
	@Action(value="ajaxFileDownload", 
			results={@Result(name=NONE, type="stream",
					params={"inputName","inputStream",
							"contentDisposition","attachment;filename=${fileName}",
							"bufferSize","4096"})})
	public String ajaxFileDownload() throws Exception {
		File file = fileSystem.getFile(fileID);
		if(null !=file && file.exists()){
			String agent = request.getHeader("User-Agent");
			boolean isMSIE = (agent != null) && (agent.toLowerCase().indexOf("firefox") != -1);
			String fileName = file.getName();
			if (isMSIE) {
				fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
			} else {
				fileName = URLEncoder.encode(fileName, "UTF-8");
			}
			setFileName(fileName);
			setInputStream(new FileInputStream(file));
		} 
		return ActionSupport.NONE;
	}

	public InputStream getInputStream() throws Exception {		
		return inputStream; 
	}
}